package cn.net.xyan.blossom.webUI.service

import cn.net.xyan.blossom.dto.WebCatalog
import cn.net.xyan.blossom.dto.WebCatalogItem
import cn.net.xyan.blossom.security.service.AuthService
import cn.net.xyan.blossom.webUI.dao.CatalogDao
import cn.net.xyan.blossom.webUI.dao.CatalogItemDao
import cn.net.xyan.blossom.webUI.entity.Catalog
import cn.net.xyan.blossom.webUI.entity.CatalogItem
import cn.net.xyan.blossom.webUI.utils.webApplicationContext
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.web.context.WebApplicationContext
import javax.annotation.PostConstruct

interface CatalogService{
    fun setupCatalog(req:WebCatalog):Catalog
    fun queryCatalog(code:String):Catalog?
    fun saveCatalog(req:WebCatalog):Catalog

    fun setupCatalogItem(req: WebCatalogItem): CatalogItem
    fun queryCatalogItem(code:String):CatalogItem?
    fun saveCatalogItem(req:WebCatalogItem):CatalogItem
}


class DefaultCatalogServiceImpl:CatalogService{

    @Autowired
    lateinit var catalogDao:CatalogDao

    @Autowired
    lateinit var itemDao:CatalogItemDao

    @Autowired
    lateinit var authService:AuthService

    @Autowired
    lateinit var wac :WebApplicationContext

    @PostConstruct
    fun setup(){
        webApplicationContext = wac
    }

    override fun setupCatalog(req: WebCatalog): Catalog {
        return queryCatalog(req.code)?: saveCatalog(req)
    }

    override fun queryCatalog(code: String): Catalog? {
        return catalogDao.findOne(code)
    }

    override fun saveCatalog(req: WebCatalog): Catalog {
        val catalog = queryCatalog(req.code)?: Catalog(req.code,req.title)
        if (req.permission!= null){
            val p = authService.setupPermission(req.permission!!)
            catalog.permission = p
        }

        return catalogDao.saveAndFlush(catalog)
    }

    override fun setupCatalogItem(req: WebCatalogItem): CatalogItem {
        return queryCatalogItem(req.code)?:saveCatalogItem(req)
    }

    override fun queryCatalogItem(code: String): CatalogItem? {
        return itemDao.findOne(code)
    }

    override fun saveCatalogItem(req: WebCatalogItem): CatalogItem {
        val catalogItem = queryCatalogItem(req.code)?: CatalogItem(req.code,req.title)
        if (req.permission != null){
            val p = authService.setupPermission(req.permission!!)
            catalogItem.permission = p
        }
        if (req.catalogCode!=null){
            val catalog = queryCatalog(req.catalogCode!!)
            catalogItem.catalog = catalog
        }

        if (req.viewName!= null){
            catalogItem.viewName = req.viewName
        }
        if (req.viewParam!=null){
            catalogItem.viewParam = req.viewParam
        }

        return itemDao.saveAndFlush(catalogItem)
    }

}